/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BaseActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.app.SkinAppCompatDelegateImpl;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.github.ybq.android.spinkit.style.Wave;
import com.umeng.analytics.MobclickAgent;

import io.bhex.app.R;
import io.bhex.app.account.utils.LocalManageUtil;
import io.bhex.app.broadcast.receiver.HomeKeyEventBroadCastReceiver;
import io.bhex.app.main.ui.MainActivity;
import io.bhex.app.utils.ActivityCache;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.SystemBarTintManager;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.mvp.BaseMVPActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.mvp.BaseUI;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.app.AppStatusConstant;
import io.bhex.sdk.app.AppStatusManager;


public abstract class BaseActivity<P extends BasePresenter<V>, V extends AppUI & BaseUI> extends BaseMVPActivity<P, V> implements AppUI {
    protected HomeKeyEventBroadCastReceiver receiver;
    private Dialog dialog;
    private int dialogRef;
    public static final String INTENT_KEY_FROM_NOTIFICATION = "from.notification";
    protected boolean fromNotification;

    public NotifyFragment mOnNotifyFragment;

    //是否需要从Activity管理中移除 1 需要 0 不需要
    protected int misNeedRomve = 1;

    @NonNull
    @Override
    public AppCompatDelegate getDelegate() {
        return SkinAppCompatDelegateImpl.get(this, this);
    }

    public interface NotifyFragment{
        void onNotifyFragment();

    }
    public void setOnNotifyFragment(NotifyFragment onNotifyFragment) {
        mOnNotifyFragment = onNotifyFragment;
    }

    @Override
    public void startActivity(Intent intent) {
//        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        super.startActivity(intent);
        overridePendingTransition(0,0);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if(fragment instanceof NotifyFragment){
            setOnNotifyFragment((NotifyFragment)fragment);
        }
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.attachBaseContext(newBase,""));
        //Log.d("SplashActivity:", "BaseActivity==>"+RateAndLocalManager.getSetLocale().getLanguage());

    }

    public void FragmentNotifyActivity(){
        if(mOnNotifyFragment != null)
            mOnNotifyFragment.onNotifyFragment();
    }

    @Override
    public Resources getResources() {
//        return super.getResources();
        //TODO 待验证 默认系统设置 防止用户个性化修改系统字体大小，导致UI适配问题
        Resources res = super.getResources();
        if(res.getConfiguration().fontScale != 1){
            Configuration config = new Configuration();
            config.setToDefaults();
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
        return res;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getResources();

        //后台回收了，则重启APP
        switchAppStatus(AppStatusManager.getInstance().getAppStatus());
//        DesityUtils.setCustomDesity(this,BHexApplication.getInstance());
        initSystemBarTint();
        ActivityCache.getInstance().addActivity(this);
        receiver = new HomeKeyEventBroadCastReceiver();
        registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
        dialogRef = 0;
        /*if(isStatusColorDefault()){
            StatusBarExtUtil.setStatusColor(this,false,true,SkinColorUtil.getWhite(this));
        }*/
        //RateAndLocalManager.GetInstance(this).SetCurLocalKind(RateAndLocalManager.GetInstance(this).getCurLocalKind());
    }

    @Override
    protected void setContentViewExt() {
        int view = getContentView();
        if (view != -1) {//启动activity不需要setContentView，所以在此加上临时判断
            setContentView(view);
            initView();
            addEvent();
        }
    }

    protected abstract int getContentView();

    protected void initView() {
    }

    protected void addEvent() {
    }

    /**是否需要登录状态********/
    protected boolean isNeedLogin(){
        return false;
    }


    protected void setTopbarNight(TopBar topBar){
        topBar.setLeftImg(R.mipmap.btn_head_back);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        checkBackgroundTime();
        boolean isSkinBlackMode = SPEx.get(AppData.SPKEY.SKIN_IS_BLACK_MODE, false);
//        myStatusBar.setBackgroundColor(isSkinBlackMode ? getResources().getColor(R.color.color_bg_2_night) : getResources().getColor(R.color.color_bg_2));
        if (isSkinBlackMode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //实现状态栏图标和文字颜色为浅色
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, 0);
            }

        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //实现状态栏图标和文字颜色为暗色
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, 0);
            }

        }
        if (getIntent() != null) {
            fromNotification = getIntent().getBooleanExtra(INTENT_KEY_FROM_NOTIFICATION, false);

        }

    }

    /** 子类可以重写改变状态栏颜色 */
    protected int setStatusBarColor() {
        return getColorPrimary();
    }

    /** 子类可以重写决定是否使用透明状态栏 */
    protected boolean translucentStatusBar() {
        return false;
    }

    /** 设置状态栏颜色 */
    protected void initSystemBarTint() {
        Window window = getWindow();
        if (translucentStatusBar()) {
            // 设置状态栏全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            return;
        }
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0以上使用原生方法

            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(setStatusBarColor());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(setStatusBarColor());
        }
    }

    /**
     * 切换状态栏
     * @param isTransparent
     */
    protected void switchStatusBar(boolean isTransparent){
        Window window = getWindow();
        if (isTransparent) {
            // 设置状态栏全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            return;
        }
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0以上使用原生方法
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(setStatusBarColor());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(setStatusBarColor());
        }
    }

    /** 获取主题色 */
    public int getColorPrimary() {
        return  ContextCompat.getColor(this,CommonUtil.isBlackMode()?R.color.color_bg_2_night:R.color.color_bg_2);
//        TypedValue typedValue = new TypedValue();
//        getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
//        return typedValue.data;
    }

    /** 初始化 Toolbar */
    public void initToolBar(Toolbar toolbar, boolean homeAsUpEnabled, String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(homeAsUpEnabled);
    }

    public void initToolBar(Toolbar toolbar, boolean homeAsUpEnabled, int resTitle) {
        initToolBar(toolbar, homeAsUpEnabled, getString(resTitle));
    }

    //检查APP在后台的时间
    private void checkBackgroundTime() {
            //判断是否压入后台
//            if (!AppData.isHome||AppData.isFirstLaunch) {
            if (!AppData.isHome) {
                return;
            }
            if (System.currentTimeMillis() - AppData.HOME_TIME > AppData.HOME_ALLOW_TIME) {
                SPEx.setFingerAuth(false);
                if (isNeedLogin()) {
                    UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_BASE_INTERCEPT);
                }
//                AppData.HOME_LOCKED = true; //开启APP锁
//                boolean fingerOpen = SPEx.get(AppData.SPKEY.FINGER_PWD_KEY,false);
//                if (fingerOpen) {//开启了指纹
//                    if (SafeUilts.isFinger(this)) {
//                        IntentUtils.openFinger(this);
//                    }else{
//                        //此处校验，如果用户删除了设备指纹，此时自动退出用户信息，删除指纹开启设置
//                        UserInfo.clearUserInfo();
//                        SPEx.remove(AppData.SPKEY.FINGER_PWD_KEY);
//                    }
//                }else{
//                    String gesturePwd = SPEx.get(AppData.SPKEY.GESTURE_PWD_KEY,"");
//                    if (!TextUtils.isEmpty(gesturePwd)) {//开启了手势
//
//                        IntentUtils.openGestureVerify(this);
//                    }
//                }
            } else {
                AppData.HOME_TIME = System.currentTimeMillis();
            }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        if(misNeedRomve>0){
            //ActivityCache.getInstance().removeActivity(this);
        }
        if (fromNotification) {

            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);

        }
        super.onDestroy();
    }
    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    public void showProgressDialog(){
        showProgressDialog("","");
    }

    public void showProgressDialog(String title, String hint) {
        if (!isAlive())
            return;

        dialogRef++;

        if (dialog != null && dialog.isShowing())
            return;


        if (dialog == null) {
            dialog = new Dialog(this, R.style.dialogLoading);
            dialog.setContentView(R.layout.loading_waiting_layout);
            ProgressBar progressBar = dialog.findViewById(R.id.bar_loading);
//        RotatingPlane animDrawable = new RotatingPlane();
//        DoubleBounce animDrawable = new DoubleBounce();
            Wave animDrawable = new Wave();
//        WanderingCubes animDrawable = new WanderingCubes();
//        Pulse animDrawable = new Pulse();
//        PulseRing animDrawable = new PulseRing();
//        ChasingDots animDrawable = new ChasingDots();
//        ThreeBounce animDrawable = new ThreeBounce();
//        Circle animDrawable = new Circle();
//        CircleSprite animDrawable = new CircleSprite();
//        FadingCircle animDrawable = new FadingCircle();
//        FoldingCube animDrawable = new FoldingCube();
//        RotatingCircle animDrawable = new RotatingCircle();
//                CubeGrid animDrawable = new CubeGrid();
            animDrawable.setColor(SkinColorUtil.getDark80(this));
            progressBar.setIndeterminateDrawable(animDrawable);
        }

        if (!TextUtils.isEmpty(title))
            dialog.setTitle(title);
        if (!TextUtils.isEmpty(hint))
            ((TextView) dialog.findViewById(R.id.loading_hint_text)).setText(hint);

        dialog.show();
    }

    public void dismissProgressDialog() {
        if (isAlive() && dialog != null && --dialogRef <= 0)
            dialog.dismiss();
    }

    /**
     * 打开软键盘
     *
     * @param textView
     */
    public void openKeyBoard(TextView textView) {
        KeyBoardUtil.openKeybord(textView, this);
    }

    /**
     * 关闭软键盘
     *
     * @param textView
     */
    public void closeKeyBoard(TextView textView) {
        KeyBoardUtil.closeKeybord(textView, this);
    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyBoard() {
        KeyBoardUtil.hideKeyboard(this);
    }

    public void switchAppStatus(int appStatus) {
        switch (appStatus){
            case AppStatusConstant.STATUS_FORCE_KILLED:
                restartApp();
                break;
            case AppStatusConstant.STATUS_NORMAL:
//                setUpViewAndData();
                break;
        }
    }
    protected void restartApp() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(AppStatusConstant.KEY_HOME_ACTION,AppStatusConstant.ACTION_RESTART_APP);
        startActivity(intent);
    }

    /**
     * 设置状态栏默认颜色  白底黑字
     * @return
     */
    protected boolean isStatusColorDefault(){
        return true;
    }

}
